<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" destroy-on-close width="60%">
    <ProtectGear
      ref="protectGearRef"
      :default-type="currentSelectType === 'personal' ? 1 : 2"
      :disable-type-select="true"
      :show-checkbox="true"
      :selected-items="selectedItems"
      @cancel="dialogVisible = false"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ currentSelectType === 'personal' ? '确认添加个人装备' : '确认添加防护设施' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ProtectGear from '@/views/system/protectgear/index.vue'
import { ProtectGearApi } from '@/api/system/protectgear'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  type: {
    type: String as () => 'personal' | 'facilities',
    required: true
  },
  currentRow: {
    type: Object,
    required: true
  },
  selectedItems: {
    type: Array as () => { name: string; id: number | null }[],
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'select'])

// 计算属性和响应式变量
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const dialogTitle = computed(() =>
  props.type === 'personal' ? '选择个人防护装备' : '选择防护设施'
)

const currentSelectType = computed(() => props.type)

// 组件引用
const protectGearRef = ref()

// 监听弹窗显示状态，当弹窗打开时设置已选中的项
watch(dialogVisible, async (newVal) => {
  if (newVal) {
    await nextTick()
    if (protectGearRef.value?.preSelect) {
      console.log('设置选中项:', props.selectedItems)
      protectGearRef.value.preSelect(props.selectedItems)
    }
  }
})

// 确认选择方法
const handleConfirm = async () => {
  try {
    // 获取选中的防护装备列表
    const selectedList = protectGearRef.value?.getSelectedItems() || []

    if (selectedList.length === 0) {
      ElMessage.warning('请至少选择一项')
      return
    }

    // 获取当前行已有的防护ID列表
    const existingIds =
      props.type === 'personal'
        ? props.currentRow.personalProtectionIds || []
        : props.currentRow.protectiveFacilitiesIds || []

    // 找出新增的防护ID
    const newSelectedIds = selectedList
      .map((item) => item.id)
      .filter((id) => !existingIds.includes(id))

    // 只对新增的防护更新创建时间
    if (newSelectedIds.length > 0) {
      await ProtectGearApi.updateCreateTime(newSelectedIds)
    }

    // 创建新的数组
    const newList = selectedList.map((item) => item.name)
    const newIds = selectedList.map((item) => item.id)

    console.log('防护选择确认，类型:', props.type)
    console.log('选择的列表:', newList)
    console.log('选择的ID列表:', newIds)

    emit('select', {
      type: props.type,
      list: newList,
      ids: newIds
    })

    // 关闭弹窗
    dialogVisible.value = false
  } catch (error) {
    console.error('更新创建时间失败:', error)
    ElMessage.error('更新创建时间失败')
  }
}

// 暴露方法
const preSelect = async (selectedItems: { name: string; id: number | null }[]) => {
  await nextTick()
  if (protectGearRef.value?.preSelect) {
    console.log('设置选中项:', selectedItems)
    protectGearRef.value.preSelect(selectedItems)
  }
}

defineExpose({
  preSelect
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  padding: 10px 20px;
  text-align: right;

  .el-button + .el-button {
    margin-left: 10px;
  }
}
</style>
